package com.polaris.live.utils.viewscope

import android.view.View
import kotlinx.coroutines.Job
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext

/**
 * ViewAutoDisposeInterceptor 协程自动拦截器
 * @author Created by 天晴 on 2024/1/10 9:04
 * @since 1.0.0
 **/
class ViewAutoDisposeInterceptor(
    val view: View,
) : ContinuationInterceptor {
    override val key: CoroutineContext.Key<*>
        get() = ContinuationInterceptor

    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
        val job = continuation.context[Job]
        if (job != null) {
            view.addOnAttachStateChangeListener(ViewStateListener(view, job))
        }
        return continuation
    }
}